<?php

namespace app\api\controller;

use app\BaseController;
use app\model\Config;

class ShortUrl extends BaseController
{
    protected $middleware = [
        \app\middleware\ApiChannel::class  => ['except' => ['resolve']],
        \app\middleware\ApiUserAuthV2::class => ['except' => ['resolve']],
    ];

    /**
     * 生成短链接
     */
    public function generate()
    {

        $params = input();

        if ($msg = dmjValidate([
            'url' => 'require',
        ], [], $params)) {
            return fail($msg);
        };


        $url = $params['url'] ?? '';

        unset($params['url']);

        $obj = new \app\api\model\ShortUrl([
            'url' => $url,
            'params' => $params,
        ]);

        $obj->save();

        /** @var Config $config */
        $config = Config::query()->where('type','short_kuaizhan')->find();

        $kuaizhan = $config->value.'?code=' . alphaID($obj->id);

        return success('', [
            'url' => $kuaizhan,
            'qr' => env('app.api_url').'/qr?code='.$kuaizhan.'&isShowCode=false',
            'shareBgAround' => env('app.api_url').'/static/images/home/share_bg_around.png',
            'shareBgDiscount' => env('app.api_url').'/static/images/home/share_bg_discount.png',
            'shareBgMovie' => env('app.api_url').'/static/images/home/share_bg_movie.png',
            'shareBgQuanyi' => env('app.api_url').'/static/images/home/share_bg_quanyi.png',
            'shareBgSeckill' => env('app.api_url').'/static/images/home/share_bg_seckill.png',
            'shareBgSkittles' => env('app.api_url').'/static/images/home/share_bg_skittles.png',
            'shareBgTravelOil' => env('app.api_url').'/static/images/home/share_bg_travel_oil.png',
        ]);

    }


    /**
     * 解析
     */
    public function resolve()
    {

        $params = input();

        if ($msg = dmjValidate([
            'code' => 'require',
        ], [], $params)) {
            return fail($msg);
        }

        $id = alphaID($params['code']);

        $data = \app\model\ShortUrl::query()->where('id', $id)->find();

        return success('', $data);

    }


}